/**
 * Created by Administrator on 2017/8/3.
 */
import Vue from 'vue'
import Router from 'vue-router'
import YDUI from 'vue-ydui'
import WebIM from '../webimjs/Lib/WebIM'
import store from '../../vuex/store'
import 'vue-ydui/dist/ydui.rem.css'


import login from './pages/login.vue'
import reg from './pages/regim.vue'
import chat from './pages/chat.vue'

Vue.use(YDUI)
Vue.use(Router)
const router = new Router({
  routes: [
    {
      path: '/',
      name: 'login',
      component: login
    },
    {
      path: '/reg',
      name: 'reg',
      component: reg
    },
    {
      path: '/chat',
      name: 'chat',
      component: chat
    }
  ]
})


WebIM.conn.listen({
  // xmpp连接成功
  onOpened: (msg) => {
    console.log('login2017')
    // 如果isAutoLogin设置为false，那么必须手动设置上线，否则无法收消息
    // 手动上线指的是调用conn.setPresence(); 如果conn初始化时已将isAutoLogin设置为true
    // 则无需调用conn.setPresence();
    WebIM.conn.setPresence();

  },
  // 出席消息
  onPresence: (msg) => {
    switch (msg.type) {
      case 'subscribe':

        // 加好友时双向订阅过程，所以当对方同意添加好友的时候
        // 会有一步对方自动订阅本人的操作，这步操作是自动发起
        // 不需要通知提示，所以此处通过state=[resp:true]标示
        if (msg.status === '[resp:true]') {
          return
        }

        break;
      case 'subscribed':
        break;
      case 'unsubscribe':
        // TODO: 局部刷新
        break;
      case 'unsubscribed':
        // 好友退订消息
        break;
    }
  },
  // 各种异常
  onError: (error) => {
    console.log(error)
    // 16: server-side close the websocket connection
    if (error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED) {
      console.log('WEBIM_CONNCTION_DISCONNECTED', WebIM.conn.autoReconnectNumTotal, WebIM.conn.autoReconnectNumMax);
      if (WebIM.conn.autoReconnectNumTotal < WebIM.conn.autoReconnectNumMax) {
        return;
      }
      console.log('Error', 'server-side close the websocket connection')
      return;
    }
    // 8: offline by multi login
    if (error.type == WebIM.statusCode.WEBIM_CONNCTION_SERVER_ERROR) {
      console.log('WEBIM_CONNCTION_SERVER_ERROR');
      console.log('Error', 'offline by multi login')
      return;
    }
    if (error.type == 1) {
      let data = error.data ? error.data.data : ''
      data && console.log('Error', data)
    }
  },
  // 连接断开
  onClosed: (msg) => {
    console.log('onClosed')
  },
  // 更新黑名单
  onBlacklistUpdate: (list) => {
  },
  // 文本信息
  onTextMessage: (message) => {
    store.dispatch('fetchTextMessage', message)
    console.log('getTextMessage', message)
  },
  onPictureMessage: (message) => {
    console.log('onPictureMessage', message)
  }
})

var webimVue = new Vue({
  el: '#webim',
  router,
  store,
  template: '<router-view></router-view>',
  components: { login, reg }
})
